package cate.game.role.bag.prop.continuepack;

import cate.common.table.d.GDOperation;
import cate.common.table.item.ContinuePackRow;
import cate.game.res.MixRes;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import cate.game.role.bag.prop.Prop;
import cate.game.role.bag.prop.msg.ContinuePackDataResp;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcResult;

import java.util.HashMap;
import java.util.Map;

@NoteClass("连开礼包数据")
public class ContinuePacks extends RoleDependent {
    @NoteField("连开礼包 <物品uid, 礼包数据>")
    public Map<String, ContinuePack> packs;

    @Override
    public void initialize(Role role){
        super.initialize(role);
        if(packs == null){
            packs = new HashMap<>();
        }
        packCheck();
    }

    private void packCheck(){
        packs.entrySet().removeIf(v -> v.getValue().nextTid == 0);
    }

    public synchronized void addPack(Prop prop){
        if(prop == null || packs.containsKey(prop.uid)){
            return;
        }
        ContinuePackRow firstPackRow = role.getGame().table.item.continuePack.findFirstPack(prop.tid);
        if(firstPackRow == null){
            return;
        }
        packs.put(prop.uid, createNewPack(firstPackRow));
        noticeUpdate();
    }

    private ContinuePack createNewPack(ContinuePackRow continuePackRow){
        ContinuePack pack = new ContinuePack();
        pack.tid = 0;
        pack.nextTid = continuePackRow.id;
        pack.itemTid = continuePackRow.itemTid;
        pack.gainTime = System.currentTimeMillis();
        return pack;
    }

    public synchronized EcResult<Void> usePack(String uid, int selectedIndex){
        EcResult<Void> r = new EcResult<>();
        if(!packs.containsKey(uid)){
            return r.fail("礼包不存在");
        }
        Prop prop = role.getBag().prop.getItem(uid);
        if(prop == null){
            return r.fail("礼包不存在");
        }
        ContinuePack pack = packs.get(uid);
        r = pack.openCheck(role);
        if(!r.ok()){
            return r;
        }
        boolean openOnce = false;
        EcResult<Void> openRes;
        MixRes reward = new MixRes();
        while((openRes = pack.open(role, selectedIndex, reward)).ok()){
            openOnce = true;
        }
        if(!openOnce){
            return r.fail(openRes.message);
        }
        reward.add(role, true, GDOperation.USE_CONTINUE_PACK, prop.tid);
        role.getGame().notice.dialogReward(role, reward);
        if(pack.over()){
            //说明开到头拉
            packs.remove(uid);
            role.getBag().prop.removeItem(uid, null);
        }
        noticeUpdate();
        return r;
    }

    public void noticeUpdate(){
        role.sendNow(new ContinuePackDataResp(this));
    }

    @Override
    public void onDaySpan(boolean silence){

    }
}
